<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="76"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-del="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="showDetail(row)"
            >
              <i class="el-icon-edit-outline"></i> 查看详情
            </el-button>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item
            label="调拨单号"
            class="w50p"
            v-if="nowChanceStau != 'add'"
          >
            <el-input
              v-model="formData.transferOrderNo"
              placeholder="请输入调拨单号"
              clearable
              :disabled="nowChanceStau != 'add'"
            />
          </el-form-item>
          <div
            v-for="orderDetail,index in formData.warehousingEntryList"
            :key="index"
            class="w100p xunhuan"
          >
            <div class="goods">出库货{{ index + 1 }}</div>
            <el-form-item
              label="出货仓库 :"
              :prop="'warehousingEntryList.' + index + '.outStordocNo'"
              class="w50p"
              :rules="[{required: true,message:'出货仓库不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.outStordocNo"
                placeholder="请选择出货仓库"
                clearable
                filterable
                :disabled="nowChanceStau == 'check'"
                @change="outStordocChange($event,index)"
              >
                <el-option
                  v-for="items,indexs in stordocList"
                  :key="indexs"
                  :label="items.stordocName"
                  :value="items.stordocNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="调拨日期:"
              :prop="'warehousingEntryList.' + index + '.transferTime'"
              class="w50p"
              :rules="[{required: true,message:'调拨日期不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="orderDetail.transferTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                clearable
                placeholder="请选择时间"
                :disabled="nowChanceStau == 'check'"
                @change="transferTimeChange($event,index)"
              />
            </el-form-item>
            <el-form-item
              label="调拨货名:"
              :prop="'warehousingEntryList.' + index + '.materialNo'"
              class="w50p"
              :rules="[{required: true,message:'调拨货名不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.materialNo"
                placeholder="请选择调拨货名称"
                clearable
                filterable
                :disabled="nowChanceStau == 'check'"
                @change="getGoods($event,index)"
              >
                <el-option
                  v-for="items,indexs in materialList"
                  :key="indexs"
                  :label="items.materialName"
                  :value="items.materialNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="行号:"
              class="w50p"
              :rules="[{required: true,message:'行号不能为空',trigger:'change'}]"
            >
              <el-input
                v-model="formData.lineNum"
                :placeholder="index+1"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item
              label="选择货品批次:"
              :prop="'warehousingEntryList.' + index + '.batchObj'"
              class="w100p"
            >
              <el-select
                v-model="orderDetail.batchObj"
                placeholder="点击选择"
                filterable
                clearable
                value-key="onHandQuantityId"
                :disabled="nowChanceStau == 'check'"
                @change="batchObjChange($event, index)"
              >
                <el-option
                  v-for="item in orderDetail.batchList"
                  :key="item.onHandQuantityId"
                  :label="'批号: ' + (item.batchFile.lotNumber === undefined ? '' : item.batchFile.lotNumber) + ',  该批次现存主数量 : ' + item.onHandQuantity+ (item.cUnit.symbol || item.cUnit.unitName ) + ',  生产日期 : ' + item.batchFile.produceDate+ ',  失效日期 : ' + item.batchFile.expirationDate"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="现存主数量 :"
              :prop="'warehousingEntryList.' + index + '.nowQuantity'"
              class="w100p numberUnit block"
              :rules="[{required: true,message:'数量不能为空',trigger:'blur'},
                {pattern: /^\d+$/,message:'值该为正整数',trigger: ['change','blur']}]"
            >
              <el-input
                v-model="orderDetail.nowQuantity"
                clearable
                disabled
                class="one"
                placeholder="现存主数量"
              />
              <el-select
                v-model="orderDetail.unitNo"
                placeholder="单位"
                disabled
                clearable
                class="two"
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol || items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="调拨数量:"
              :prop="'warehousingEntryList.' + index + '.shouldArriveNum'"
              class="w50p numberUnit"
              :rules="[{required: true,message:'数量不能为空',trigger:'blur'},{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,message:'值该为大于0的数',trigger: ['blur','change']},
              ]"
            >
              <el-input
                v-model="orderDetail.shouldArriveNum"
                clearable
                class="one"
                placeholder="请输入数量"
                :disabled="nowChanceStau === 'check'"
                @input="getMainQuantity($event, index)"
              />
              <el-select
                v-model="orderDetail.castUnitNo"
                placeholder="单位"
                clearable
                class="two"
                disabled
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol || items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w50p numberUnit"
              label="主数量&主单位:"
              :prop="'warehousingEntryList.' + index + '.primaryQuantity'"
              :rules="[{pattern: /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,message:'值该为大于0的数',trigger: ['change','blur']},
                {required: true,message:'数量不能为空',trigger:['change','blur']}]"
            >
              <el-input
                class="one"
                v-model="orderDetail.primaryQuantity"
                clearable
                disabled
                placeholder="请输入主数量"
              />
              <el-select
                class="two"
                v-model="orderDetail.unitNo"
                placeholder="主单位"
                disabled
                clearable
              >
                <el-option
                  v-for="items,indexs in unitList"
                  :key="indexs"
                  :label="items.symbol || items.unitName"
                  :value="items.unitNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="生产日期:"
              :prop="'warehousingEntryList.' + index + '.produceDate'"
              class="w50p"
              :rules="[{required: true,message:'生产日期不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="orderDetail.produceDate"
                type="date"
                value-format="yyyy-MM-dd"
                disabled
                clearable
                placeholder="请选择时间"
              />
            </el-form-item>
            <el-form-item
              label="失效日期:"
              :prop="'warehousingEntryList.' + index + '.expirationDate'"
              class="w50p"
              :rules="[{required: true,message:'失效日期不能为空',trigger:'change'}]"
            >
              <el-date-picker
                v-model="orderDetail.expirationDate"
                type="date"
                value-format="yyyy-MM-dd"
                clearable
                disabled
                placeholder="请选择时间"
              />
            </el-form-item>
            <el-form-item
              label="入货仓库:"
              :prop="'warehousingEntryList.' + index + '.inStordocNo'"
              class="w50p"
              :rules="[{required: true,message:'入货仓库不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.inStordocNo"
                placeholder="请选择入货仓库"
                clearable
                filterable
                :disabled="nowChanceStau == 'check'"
              >
                <el-option
                  v-for="items,indexs in stordocList"
                  :key="indexs"
                  :label="items.stordocName"
                  :value="items.stordocNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="入库类型 :"
              :prop="'warehousingEntryList.' + index + '.warehousingType'"
              class="w50p"
              :rules="[{required: true,message:'入库类型不能为空',trigger:'change'}]"
            >
              <el-select
                v-model="orderDetail.warehousingType"
                placeholder="请选择收货仓库"
                clearable
                :disabled="nowChanceStau === 'check'"
              >
                <el-option
                  v-for="items,indexs in warehousingTypeList"
                  :key="indexs"
                  :label="items.name"
                  :value="items.name"
                />
              </el-select>
            </el-form-item>
            <div class="editBox" v-if="nowChanceStau == 'add'">
              <el-button type="info" circle @click="delOrderDetail(index)">
                <i class="el-icon-minus"></i>
              </el-button>
            </div>
          </div>
          <div v-if="nowChanceStau == 'add'">
            <el-button
              class="addone"
              type="info"
              circle
              @click="addOrderDetail"
            >
              <i class="el-icon-plus"></i>
            </el-button>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            v-if="nowChanceStau == 'add'"
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
          <el-button v-else class="zh-button-one" @click="cancel('formData')">确 认</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage"; // 仓库
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import handQuantityApi from "@/api/livestock-manage/storage-manage/quantity-on-hand"; // 现存量
import unitApi from "@/api/basic-info-manage/unit-manage"; // 单位
import allocationApi from "@/api/livestock-manage/storage-manage/allocation-manage";

export default {
  name: "SheepInformation",
  components: { SearchForm, Table, ActionBar, Pagination, BaseMainSlot },
  mixins: [mymixin],
  data() {
    return {
      searchlist: {},
      tableColumn: [
        { prop: 'transferOrderNo', label: '调拨单号', minWidth: '120px' },
        { prop: 'lineNum', label: '调拨行号', minWidth: '120px' },
        { prop: 'materialName', label: '调拨货名', minWidth: '120px' },
        { prop: 'shouldArriveNum', label: '数量', minWidth: '100px' },
        { prop: 'produceDate', label: '生产日期', minWidth: '120px' },
        { prop: 'expirationDate', label: '失效日期', minWidth: '120px' },
        { prop: 'transferTime', label: '调拨时间', minWidth: '120px' },
        { prop: 'outStordocName', label: '出库仓库', minWidth: '120px' },
        { prop: 'outboundOrderNo', label: '出库单号', minWidth: '120px' },
        { prop: 'lineNum', label: '出库行号', minWidth: '120px' },
        { prop: 'inStordocName', label: '入库仓库', minWidth: '120px' },
        { prop: 'warehousingEntryNo', label: '入库单号', minWidth: '120px' },
        { prop: 'lineNum', label: '入库行号', minWidth: '100px' },
        { prop: 'warehousingType', label: '入库类型', minWidth: '100px' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: '150' }
      ],
      formConfig: [
        {
          label: '入库类型',
          prop: 'warehousingType',
          type: 'select',
          options: [
            { name: "原材料", value: "原材料" },
            { name: "半成品", value: "半成品" },
            { name: "成品", value: "成品" }
          ],
          optionKey: { label: 'name', value: 'value' },
        },
        {
          label: '入库单号',
          prop: 'warehousingEntryNo',
          type: 'input',
        },
        {
          label: '调拨时间',
          prop: 'transferTime',
          type: 'daterange',
        },
        {
          label: '入库仓库',
          prop: 'inStordocNo',
          type: 'select',
          optionKey: { label: 'stordocName', value: 'stordocNo' },
        },
        {
          label: '调拨货名',
          prop: 'materialName',
          type: 'input',
        },
        {
          label: '出库单号',
          prop: 'outboundOrderNo',
          type: 'input',
        },
        {
          label: '出库仓库',
          prop: 'outStordocNo',
          type: 'select',
          optionKey: { label: 'stordocName', value: 'stordocNo' },
        },
      ],
      selectedList: [],
      formData: {},
      stordocList: [],
      materialList: [],
      batchList: [],
      unitList: [],
      warehousingTypeList: [
        { name: "成品", value: "成品" },
        { name: "半成品", value: "半成品" },
        { name: "原材料", value: "原材料" }
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created () {
    this.getOption()
    this.search();
  },
  methods: {
    // 获取仓库&所有物料
    getOption () {
      // 获取仓库
      warehouseApi.conditionQuery({}).then(res => {
        if (res.code === 1) {
          this.stordocList = res.data;
          let index = this.formConfig.findIndex(el => { return el.prop == 'inStordocNo' })
          this.$set(this.formConfig[index], 'options', res.data)
          let index2 = this.formConfig.findIndex(el => { return el.prop == 'outStordocNo' })
          this.$set(this.formConfig[index2], 'options', res.data)
        }
      });
      // 所有物料
      materialApi.getqueryList({}).then(res => {
        if (res.code === 1) {
          this.materialList = res.data;
        }
      });
      // 获取单位列表
      unitApi.getPlantingUnitListByCondition({}).then(res => {
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 删除一个调拨单
    delOrderDetail(index) {
      if (this.formData.warehousingEntryList.length === 1) {
        return;
      } else {
        this.formData.warehousingEntryList.splice(index, 1);
      }
    },
    // 添加一个调拨单
    addOrderDetail() {
      this.formData.warehousingEntryList.push({});
    },
    // 出货仓库修改
    outStordocChange (e, index) {
      let allBatchList = this.formData.warehousingEntryList[index].allBatchList
      if (!allBatchList) return
      this.formData.warehousingEntryList[index].batchObj = {};
      let batchList = e ? allBatchList.filter(el => {
        return el.stordocNo == e
      }) : allBatchList;
      this.$set(this.formData.warehousingEntryList[index], 'batchList', batchList)
    },
    // 获取单个商品
    async getGoods(event, index) {
      this.formData.warehousingEntryList[index].batchObj = {};
      await handQuantityApi.conditionQuery({ materialNo: event }).then(res => {
        if (res.code === 1) {
          this.$set(this.formData.warehousingEntryList[index], 'allBatchList', [...res.data])
          let outStordocNo = this.formData.warehousingEntryList[index].outStordocNo
          let batchList = outStordocNo ? res.data.filter(el => {
            return el.stordocNo == outStordocNo
          }) : res.data;
          this.$set(this.formData.warehousingEntryList[index], 'batchList', batchList)
        }
      });
    },
    // 选择现存量来填充其他属性
    batchObjChange (event, index) {
      this.$set(this.formData.warehousingEntryList[index], 'outBatchNo', event.batchNo)
      this.$set(this.formData.warehousingEntryList[index], 'inBatchNo', event.batchNo)
      this.$set(this.formData.warehousingEntryList[index], 'castUnitNo', event.castUnitNo)
      this.$set(this.formData.warehousingEntryList[index], 'unitNo', event.unitNo)
      this.$set(this.formData.warehousingEntryList[index], 'exchangeRate', event.changerate)
      this.$set(this.formData.warehousingEntryList[index], 'nowQuantity', event.onHandQuantity)
      if (event.batchFile) {
        this.$set(this.formData.warehousingEntryList[index], 'lotNumber', event.batchFile.lotNumber)
        this.$set(this.formData.warehousingEntryList[index], 'expirationDate', event.batchFile.expirationDate)
        this.$set(this.formData.warehousingEntryList[index], 'produceDate', event.batchFile.produceDate)
      }
      this.formData = { ...this.formData }
    },
    // 判断货存量
    getMainQuantity(e, index) {
      this.formData.warehousingEntryList[index].arriveNum = e;
      this.$set(this.formData.warehousingEntryList[index], 'primaryQuantity', e * this.formData.warehousingEntryList[index].exchangeRate)
      if (
        this.formData.warehousingEntryList[index].primaryQuantity >
        this.formData.warehousingEntryList[index].nowQuantity
      ) {
        this.$message.warning("出货数量大于现存数量，请重新选择出货数量");
        this.formData.warehousingEntryList[index].shouldArriveNum = "";
      }
    },
    transferTimeChange (e, index) {
      this.formData.warehousingEntryList[index].outTime = e;
      this.formData.warehousingEntryList[index].intoTime = e;
    },
    // 获取表格数据
    getTableDataList() {
      this.loading = true;
      let searchlist = { ...this.searchlist }
      if (searchlist.transferTime && searchlist.transferTime.length == 2) {
        searchlist.startTime = this.dateToFormattwo(this.searchlist.transferTime[0])
        searchlist.endTime = this.dateToFormattwo(this.searchlist.transferTime[1])
        delete searchlist.transferTime
      }
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: searchlist
      };
      allocationApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedList = [];
      this.selectedList = list.map(item => item.stordocNo);
      if (this.selectedList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      allocationApi
        .numberBatchDel({ noList: this.selectedList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          allocationApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = {
        warehousingEntryList: [{}]
      };
      this.nowChanceStau = "add";
      this.titleText = "仓库调拨";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    async showDetail (row) {
      this.formData = {
        transferOrderNo: row.transferOrderNo,
        warehousingEntryList: [row]
      };
      await this.getGoods(row.materialNo, 0)
      let data = row.batchList && row.batchList.find(el => { return el.batchNo == row.outBatchNo })
      if (data) {
        this.$set(this.formData.warehousingEntryList[0], 'batchObj', data)
        this.$set(this.formData.warehousingEntryList[0], 'nowQuantity', data.onHandQuantity)
      }

      this.nowChanceStau = "check";
      this.titleText = "调拨详情";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            let params = [...this.formData.warehousingEntryList];
            allocationApi.edit(params[0]).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let params = [
              ...this.formData.warehousingEntryList.map(el => {
                return {
                  ...el,
                  organizationNo: sessionStorage.organizationNo
                }
              })
            ];
            params.map((el, i) => {
              delete params[i].allBatchList
              delete params[i].batchList
              delete params[i].batchObj
            })
            allocationApi.addBatch(params).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 140px;
}
.xunhuan {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .goods {
    width: 100%;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }
  .editBox {
    z-index: 100;
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}
.addone {
  margin-left: 140px;
}
.numberUnit {
  display: flex;
  .one {
    width: 65%;
  }
  .two {
    width: 35%;
  }
}
.block {
  margin-right: 52%;
}
</style>
